import { VxeUI } from 'vxe-pc-ui';
import { ElImage } from 'element-plus';
import { getNestedPropertyValue } from './utils';

/**
 * 获取属性值的通用函数
 */
const getAttributeValue = (attrName, defaultValue, ...sources) => {
  for (const source of sources) {
    if (source && source[attrName] !== undefined) {
      return source[attrName];
    }
  }
  return defaultValue;
};

/**
 * 渲染图片的通用函数
 * @param {Object} renderOpts - 渲染选项
 * @param {Object} params - 参数对象
 * @returns {JSX.Element | Array<JSX.Element>} 渲染结果
 */
const renderImage = (renderOpts, params) => {
  const effectiveData = params?.row || renderOpts.row || renderOpts.data || {};
  const effectiveColumn = params?.column || renderOpts.column || {};
  const field =
    effectiveColumn.field || effectiveColumn.property || params?.field;

  if (!field) {
    console.warn('ImageRender: Missing field identifier');
    return <span>-</span>;
  }

  // 获取当前值，它可能是一个字符串，也可能是一个数组
  const cellValue = getNestedPropertyValue(effectiveData, field);

  // 如果值为空或空数组，返回占位符
  if (!cellValue || (Array.isArray(cellValue) && cellValue.length === 0)) {
    return <span>-</span>;
  }

  // 处理数组 ---
  const imageUrls = Array.isArray(cellValue) ? cellValue : [cellValue];

  // 获取配置信息
  const props = renderOpts.props || {};
  const attrs = renderOpts.attrs || {};

  // 合并所有可能的属性
  const mergedAttrs = { ...renderOpts, ...attrs, ...props };

  // 获取图片相关属性
  const className = getAttributeValue(
    'className',
    'table-list-image',
    props,
    attrs,
  );
  const fit = getAttributeValue('fit', 'cover', props, attrs);
  const lazy = getAttributeValue('lazy', false, props, attrs);
  const hideOnClickModal = getAttributeValue(
    'hideOnClickModal',
    false,
    props,
    attrs,
  );
  const previewTeleported = getAttributeValue(
    'previewTeleported',
    true,
    props,
    attrs,
  );

  // 预览列表应该是所有图片的集合
  const previewSrcList = imageUrls;

  // 遍历图片URL数组，为每个URL创建一个ElImage组件
  return (
    <div class="table-image-array-container">
      {imageUrls.map((imageUrl, index) => (
        <ElImage
          key={index}
          class={className}
          src={imageUrl}
          initial-index={index}
          previewSrcList={previewSrcList}
          fit={fit}
          lazy={lazy}
          hideOnClickModal={hideOnClickModal}
          previewTeleported={previewTeleported}
          {...mergedAttrs}
          onError={(e) => {
            console.warn('ImageRender: Failed to load image:', imageUrl);
            if (renderOpts.events?.error) {
              renderOpts.events.error(e, effectiveData, params || renderOpts);
            }
          }}
        />
      ))}
    </div>
  );
};

// 注册渲染器
VxeUI.renderer.add('RaElImageRender', {
  renderTableCell(renderOpts, params) {
    return renderImage(renderOpts, params);
  },
  renderDefault(renderOpts, params) {
    return renderImage(renderOpts, params);
  },
});

export default 'RaElImageRender';
